package com.gz.controller;

import com.gz.dto.PaperQuestionDto;
import com.gz.entity.PaperQuestion;
import com.gz.entity.TestPaper;
import com.gz.service.PaperQuestionService;
import com.gz.service.TestPaperService;
import com.gz.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * (PaperQuestion)表控制层
 *
 * @author makejava
 * @since 2024-02-26 11:20:17
 */
@RestController
@RequestMapping("paperQuestion")
@Api(value = "试卷题目关系控制层", tags = {"试卷题目关系控制层"})
public class PaperQuestionController {

  /**
   * 服务对象
   */
  @Autowired
  private PaperQuestionService paperQuestionService;
  /**
   * 服务对象
   */
  @Autowired
  private TestPaperService testPaperService;

  /**
   * 分页查询
   *
   * @param dto 筛选条件
   * @return 查询结果
   */
  @ApiOperation(value = "分页查询")
  @PostMapping("/queryPage")
  public R queryByPage(@RequestBody PaperQuestionDto dto, HttpServletRequest request) {
    return R.ok(paperQuestionService.queryByPage(dto));
  }


  /**
   * 分页查询
   *
   * @param dto 筛选条件
   * @return 查询结果
   */
  @ApiOperation(value = "条件查询")
  @PostMapping("/queryAll")
  public R queryAll(@RequestBody PaperQuestionDto dto, HttpServletRequest request) {
    return R.ok(paperQuestionService.queryAll(dto));
  }

  /**
   * 通过主键查询单条数据
   *
   * @param id 主键
   * @return 单条数据
   */
  @ApiOperation(value = "主键查询")
  @GetMapping("/queryById")
  public R<PaperQuestion> queryById(@RequestParam("id") Integer id) {
    return R.ok(paperQuestionService.queryById(id));
  }

  /**
   * 新增数据
   *
   * @param paperQuestion 实体
   * @return 新增结果
   */
  @ApiOperation(value = "新增数据")
  @PostMapping("/saveOld")
  public R<PaperQuestion> add(@RequestBody PaperQuestion paperQuestion) {
    if (StringUtils.isEmpty(paperQuestion.getPaperId())) {
      return R.failure("试卷id不能为空");
    }
    String paperId = paperQuestion.getPaperId();
    /** 先查是否已经录满 */
    TestPaper testPaper = testPaperService.queryById(Integer.parseInt(paperId));
    PaperQuestionDto dto = new PaperQuestionDto();
    dto.setPaperId(paperId);
    List<PaperQuestion> existQt = paperQuestionService.queryAll(dto);
    if (CollectionUtils.isNotEmpty(existQt)) {
      for (PaperQuestion a : existQt) {
        if (a.getQuestionId().equals(paperQuestion.getQuestionId())) {
          return R.failure("此题目:" + a.getQuestionId() + "已经录入过");
        }
      }
    }
    if (null == testPaper.getEnteredQtCnt()) {
      testPaper.setEnteredQtCnt(0);
    }
    if (testPaper.getEnteredQtCnt() >= testPaper.getQuestionCount()) {
      return R.failure("您的试卷题目已经录满");
    }
    PaperQuestion insert = paperQuestionService.insert(paperQuestion);
    TestPaper paperParam = new TestPaper();
    paperParam.setId(testPaper.getId());
    /** 录入题目后，剩余题目数，自然就减1 */
    paperParam.setLeftPosCnt(testPaper.getLeftPosCnt() - 1);
    paperParam.setEnteredQtCnt(testPaper.getEnteredQtCnt() + 1);
    testPaperService.update(paperParam);
    return R.ok(insert);
  }
  /**
   * 录入题目
   *
   * @param paperQuestion 实体
   * @return 新增结果
   */
  @ApiOperation(value = "新增数据")
  @PostMapping("/save")
  public R savePaperQuestion(@RequestBody PaperQuestion paperQuestion) {
    return paperQuestionService.saveData(paperQuestion);
//    return R.ok(insert);
  }

  /**
   * 批量编辑数据
   *
   * @param list
   * @return 编辑结果
   */
  @ApiOperation(value = "批量新增数据")
  @PostMapping("/insertBatch")
  @Transactional
  public R insertBatch(@RequestBody List<PaperQuestion> list) {
    String paId = "";
    if (CollectionUtils.isNotEmpty(list)) {
      paId = list.get(0).getPaperId();
    }
    /** 查看批量待插入题目的 */
    List<String> paperIds = list.stream().map(PaperQuestion::getPaperId).distinct()
        .collect(Collectors.toList());
    if (CollectionUtils.isNotEmpty(paperIds) && paperIds.size() > 1) {
      return R.failure("批量录入题目只能录入单张试卷");
    }
    List<String> collect = list.stream().map(PaperQuestion::getQuestionId).distinct()
        .collect(Collectors.toList());
    List<String> existQtIds = new ArrayList<>();
    List<String> newQtIds = new ArrayList<>();
    /** 卷子id */
    String paperId = "";
    /** 卷子设置题目数量 */
    Integer paQtCnt = 0;
    /** 卷子已经录入题目数量 */
    Integer paExsQtCnt = 0;
    if (CollectionUtils.isNotEmpty(list)) {
      paperId = list.get(0).getPaperId();
    }
    /** 先查是否已经录满 */
    TestPaper testPaper = testPaperService.queryById(Integer.parseInt(paId));
    if(null==testPaper.getEnteredQtCnt()){
      testPaper.setEnteredQtCnt(0);
    }
    if (testPaper.getEnteredQtCnt() >= testPaper.getQuestionCount()) {
      return R.failure("您的试卷题目已经录满");
    }
    Integer leftPosCnt = testPaper.getLeftPosCnt();
    /** 查待录入题目数量是否已经超出剩余题目数量 */
    if (leftPosCnt > 0 && CollectionUtils.isNotEmpty(list) && list.size() > leftPosCnt) {
      return R.failure("您要批量录入题目的数量已超越试卷可录入题目剩余数量");
    }
    int i = 0;
    if (leftPosCnt > 0 && CollectionUtils.isNotEmpty(list) && list.size() <= leftPosCnt) {
      if (collect.size() < list.size()) {
        return R.failure("有重复题目");
      }
      PaperQuestionDto dto = new PaperQuestionDto();
      dto.setPaperId(paperId);
      List<PaperQuestion> paperQuestions = paperQuestionService.queryAll(dto);
      List<PaperQuestion> existQt = new ArrayList<>();
      /** 判断哪些是已经录入过的题目 */
      for (PaperQuestion itm : list) {
        for (PaperQuestion ext : paperQuestions) {
          if (null != itm.getQuestionId() && ext.getQuestionId().equals(itm.getQuestionId())) {
            existQt.add(itm);
          }
        }
      }
      /** 拿到所有已存在题目id */
      existQtIds = existQt.stream().map(a -> {
            return a.getQuestionId();
          })
          .collect(Collectors.toList());
      /** 过滤出不存在题目 */
      List<String> finalExistQtIds = existQtIds;
      list = list.stream().filter(a -> !finalExistQtIds.contains(a.getQuestionId())).distinct()
          .collect(Collectors.toList());
      newQtIds = list.stream().map(PaperQuestion::getQuestionId)
          .collect(Collectors.toList());
      /** 批量插入题目 */
      i = paperQuestionService.insertBatch(list);
      TestPaper paperParam = new TestPaper();
      paperParam.setId(Integer.parseInt(paId));
      /** 录入题目后，剩余题目数，自然就减1 */
      paperParam.setLeftPosCnt(testPaper.getLeftPosCnt() - list.size());
      paperParam.setEnteredQtCnt(testPaper.getEnteredQtCnt() + list.size());
      testPaperService.update(paperParam);
    }
    return R.ok("已存在题目id集合:" + existQtIds + ";新增题目id集合:" + newQtIds,"已存在题目id集合:" + existQtIds + ";新增题目id集合:" + newQtIds);
  }

  /**
   * 编辑数据
   *
   * @param paperQuestion 实体
   * @return 编辑结果
   */
  @ApiOperation(value = "编辑数据")
  @PostMapping("/update")
  public R<PaperQuestion> edit(@RequestBody PaperQuestion paperQuestion) {
    return R.ok(paperQuestionService.update(paperQuestion));
  }

  /**
   * 批量编辑数据
   *
   * @param list
   * @return 编辑结果
   */
  @ApiOperation(value = "批量编辑数据")
  @PostMapping("/updateBatch")
  public R<?> editBatch(@RequestBody List<PaperQuestion> list) {
    return R.ok(paperQuestionService.updateBatch(list));
  }

  /**
   * 删除数据
   *
   * @param id 主键
   * @return 删除是否成功
   */
  @GetMapping("/deleteById")
  @ApiOperation(value = "删除数据")
  public R<Boolean> deleteById(@RequestParam("id") Integer id) {
    return R.ok(paperQuestionService.deleteById(id));
  }

}

